package com.hongyuan.sellfitness.ui.message.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.google.android.material.tabs.TabLayoutMediator;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.base.CustomFragment;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.databinding.FragmentMessageBinding;
import com.hongyuan.sellfitness.pushservice.MssagePosition;
import com.hongyuan.sellfitness.ui.Page2Adapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.tatarka.bindingcollectionadapter2.BR;

public class MessageFragment extends CustomFragment<FragmentMessageBinding, CustomViewModel> {

    private Disposable mSubscription;

    private List<CustomFragment> fragments;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_message;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();

        //初始化数据
        fragments = new ArrayList<>();
        fragments.add(new MessageLetterFragment().setTabTag("私信"));
        fragments.add(new MessageCommentaryFragment().setTabTag("评论"));
        fragments.add(new MessagePraiseFragment().setTabTag("赞"));
        fragments.add(new MessageFansFragment().setTabTag("粉丝"));

        binding.viewPager.setAdapter(new Page2Adapter(getActivity(),fragments));
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(binding.layoutMenu, binding.viewPager, (tab, position) -> {
            CustomFragment f = fragments.get(position);
            tab.setText(f.getTabTag());
        });
        tabLayoutMediator.attach();

        mSubscription = RxBus.getDefault().toObservable(MssagePosition.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(mssagePosition -> {
                    //显示那一页
                    binding.viewPager.setCurrentItem(mssagePosition.getPosition());
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

}
